<?php
class Zen_Filter_TreeList {
	protected $dbdata;
	protected $data;
	protected $map;
	protected $res;
	protected $id="id";
	protected $name = 'label';
	private function mapArray() {
		foreach ( $this->dbdata as $arr ) {
			$this->map [$arr ['parent_id']] [$arr ['left']] = $arr ['id'];
			$this->data [$arr ['id']] = $arr;
		}
		foreach ( $this->map as $key => $value ) {
			ksort ( $value );
			$this->map [$key] = $value;
		}
	}
	
    /**
	 * @return the $id
	 */
	public function getId() {
		return $this->id;
	}

	/**
	 * @return the $name
	 */
	public function getName() {
		return $this->name;
	}

	/**
	 * @param $id the $id to set
	 */
	public function setId($id) {
		$this->id = $id;
	}

	/**
	 * @param $name the $name to set
	 */
	public function setName($name) {
		$this->name = $name;
	}

	private function fillarray ($node = 0, $level)
    {
        $nodes=array();
        foreach ($this->map[$node] as $key=>$child) {
            $node=$this->data[$child];
            if (isset($this->map[$child])) {
               $node['children']=$this->fillarray($child, $level + 1);
            }
            $nodes[]=$node;
        }
        return $nodes;
    }
	
	private function implodeArray($data, $level) {
		foreach ( $data as $node ) {
			$pref = "";
			for($i = 1; $i <= $level; $i ++) {
				$pref .= "--";
			}
			$this->res [$node [$this->id]] = $pref . $node [$this->name];
			if (isset ( $node ['children'] )) {
				$this->implodeArray ( $node ['children'], $level + 1 );
			}
			
		}
	
	}
	
	public function filter($data) {
		if(sizeof($data)>0){
		$this->dbdata = $data;
		$this->mapArray ();
		$res = $this->fillarray ( '0', 1 );
		$this->implodeArray ( $res, 0 );
		return $this->res;}
		else{
			return array();
		}
	}
}